package com.sunday.common.core.utils;

import com.sunday.common.core.constants.StringConstants;

import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串 工具类
 *
 * @author zsy
 * @since 2022/10/10
 */
public class StringUtils {

    /**
     * 首写字母大写
     *
     * @param str
     * @return {@link String}
     */
    public static String capitalize(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    /**
     * 首写字母小写
     *
     * @param str
     * @return {@link String}
     */
    public static String lowercase(String str) {
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }

    /**
     * 驼峰转小写 并按照指定字符串分割
     *
     * @param str
     * @param delimiter
     * @return {@link String}
     */
    public static String humpToLowerDelimiter(String str, String delimiter) {
        Pattern compile = Pattern.compile("[A-Z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, delimiter + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 通过 get/set/is 开头的方法，获取属性名称
     *
     * @param name
     * @return {@link String}
     */
    public static String resolveFieldName(String name) {
        if (name.startsWith("get") || name.startsWith("set")) {
            name = name.substring(3);
        } else if (name.startsWith("is")) {
            name = name.substring(2);
        } else {
            throw new RuntimeException("Error parsing property name '" + name + "'.  Didn't start with 'is', 'get' or 'set'.");
        }

        if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) {
            name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
        }
        return name;
    }

    /**
     * 根据size长度，截取message信息
     *
     * @param message
     * @param size
     * @return {@link String}
     */
    public static String truncateMessage(String message, Integer size) {
        return Optional.ofNullable(message)
                .map(n -> {
                    if (n.length() > size) {
                        return n.substring(0, size);
                    } else {
                        return n;
                    }
                })
                .orElse(StringConstants.EMPTY);
    }

    /**
     * 替换换行符为空串
     *
     * @param message
     * @return {@link String}
     */
    public static String replaceNewline(String message) {
        return Optional.ofNullable(message)
                .map(n -> n.replaceAll(StringConstants.WIPE_SEP, StringConstants.EMPTY))
                .orElse(StringConstants.EMPTY);
    }

}
